package com.hmkj.web.controller.quote;

import com.alibaba.fastjson.JSON;
import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.utils.BigDecimalUtils;
import com.hmkj.common.utils.PingYinUtil;
import com.hmkj.common.utils.PriceHelper;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.core.constant.CacheID;
import com.hmkj.core.constant.ConfigNID;
import com.hmkj.core.eolinker.endpoints.QuotationEndpoint;
import com.hmkj.core.eolinker.models.*;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.order.OrderModel;
import com.hmkj.core.po.blackList.BlackList;
import com.hmkj.core.po.myChoose.MyChoose;
import com.hmkj.core.po.user.User;
import com.hmkj.core.service.blackList.BlackListService;
import com.hmkj.core.service.myChoose.MyChooseService;
import com.hmkj.core.service.quote.QuoteService;
import com.hmkj.web.controller.GenericController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 行情请求相关控制器
 *
 * @author eproo
 * @create 2018-07-13 11:57
 */
@Api(description = "行情请求相关")
@Slf4j
@RestController
@RequestMapping(GenericController.MEMBER_URL + "/quote")
public class AppQuotationController extends GenericController<Integer, User> {

    @Resource
    private QuoteService quoteService;
    @Resource
    private MyChooseService myChooseService;
    @Resource
    private BlackListService blackListService;

    @ApiOperation(value = "首页股票实时行情", notes = "首页股票实时行情")
    @ResponseBody
    @RequestMapping(value = "/realTimeJson", method = RequestMethod.POST)
    public ResultEntity realTimeJson() throws Exception {
        //2A01 深证指数  395004 创业板 1A0001上证
        //首页指数
        List<ModelIndexRealPrice> realTimeList = quoteService.findRealTimeListJson();
        return ok(CollectionUtils.isNotEmpty(realTimeList) ? "获取数据成功" : "非交易时间", realTimeList);
    }

    /**
     * 股票查询（根据名称或者代码）
     */
    @RequestMapping(value = "/searchStock", method = RequestMethod.POST)
    public ResultEntity searchStock(@ApiParam("searchVal") @RequestParam(required = true) String searchVal) throws Exception {
        List<StockListModel> resultList = new ArrayList<>();
//        User user = getLoginUser();
        if (StringUtils.isNotBlank(searchVal)) {
            //上证A股
            searchVal = searchVal.trim();
            List<StockListModel> upList = redisService.getList(CacheID.STOCK_LIST_PREFIX, StockListModel.class);
            if (null == upList) {
                return result(resultList, "行情查询为空", ResultEntity.FAIL);
            }
            int i = 0;
            for (StockListModel upStock : upList) {
                if (upStock.getCode_name().contains(searchVal) || upStock.getStock_code().contains(searchVal) || PingYinUtil.getFirstSpell(upStock.getCode_name()).contains(searchVal.trim().toUpperCase())) {
                    //判断股票是否是自选
//                    HashMap<String, Object> map = new HashMap<>();
//                    if (user != null) {
//                        MyChoose choose = myChooseService.selectOne(new MyChoose(t -> {
//                            t.setUserId(user.getId());
//                            t.setCode(upStock.getStock_code());
//                            t.setDelFlag(MyChoose.DELFLAG.NORMAL.code);
//                        }));
//                        upStock.setIsChoose(null == choose ? 0 : 1);
//                    } else {
//                        upStock.setIsChoose(0);
//                    }

                    ModelRealTime modelRealTime = QuotationEndpoint.realtime(upStock.getStock_code());
                    if(null != modelRealTime){
                        upStock.setLast_price(modelRealTime.getLast_price());
                        upStock.setRise_pre(modelRealTime.getRise_pre());
                        upStock.setRise_price(modelRealTime.getRise_price());
                    }
                    resultList.add(upStock);
                    i = i + 1;
                    if (i == 20) {
                        break;
                    }
                }
            }
        }
        return ok(resultList);
    }

    /**
     * 单个股票的信息
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getStockByCode", method = RequestMethod.POST)
    public ResultEntity getStockByCode(@ApiParam("股票代码") @RequestParam(required = true) String code) throws Exception {
        if (StringUtils.isBlank(code)) {
            //默认给一个股票代码
            code = "000001";
        }
        //获取股票信息
        ModelRealTime modelRealTime = QuotationEndpoint.realtime(code);
        String finalCode = code;
        if (modelRealTime != null) {
            //（当日最高点的价格－当日最低点的价格）/昨天收盘价×100%=振幅
            double swing = BigDecimalUtils.div(Double.parseDouble(modelRealTime.getHigh_price()) - Double.parseDouble(modelRealTime.getLow_price()), Double.parseDouble(modelRealTime.getPrev_price()), 4);
            modelRealTime.setSwing(String.valueOf(BigDecimalUtils.decimal(swing * 100, 2)));
            //涨停价 开盘价*1.1
            double upStop = Double.parseDouble(modelRealTime.getPrev_price()) * 1.1;
            modelRealTime.setUpStop(String.valueOf(BigDecimalUtils.round(upStop, 2)));
            //跌停价 开盘价*0.9
            double downStop = Double.parseDouble(modelRealTime.getPrev_price()) * 0.9;
            modelRealTime.setDownStop(String.valueOf(BigDecimalUtils.round(downStop, 2)));
            modelRealTime.setAsk_volume1(String.valueOf(BigDecimalUtils.round(Double.parseDouble(modelRealTime.getAsk_volume1()) / 100, 0)));
            modelRealTime.setAsk_volume2(String.valueOf(BigDecimalUtils.round(Double.parseDouble(modelRealTime.getAsk_volume2()) / 100, 0)));
            modelRealTime.setAsk_volume3(String.valueOf(BigDecimalUtils.round(Double.parseDouble(modelRealTime.getAsk_volume3()) / 100, 0)));
            modelRealTime.setAsk_volume4(String.valueOf(BigDecimalUtils.round(Double.parseDouble(modelRealTime.getAsk_volume4()) / 100, 0)));
            modelRealTime.setAsk_volume5(String.valueOf(BigDecimalUtils.round(Double.parseDouble(modelRealTime.getAsk_volume5()) / 100, 0)));

            modelRealTime.setBid_volume1(String.valueOf(BigDecimalUtils.round(Double.parseDouble(modelRealTime.getBid_volume1()) / 100, 0)));
            modelRealTime.setBid_volume2(String.valueOf(BigDecimalUtils.round(Double.parseDouble(modelRealTime.getBid_volume2()) / 100, 0)));
            modelRealTime.setBid_volume3(String.valueOf(BigDecimalUtils.round(Double.parseDouble(modelRealTime.getBid_volume3()) / 100, 0)));
            modelRealTime.setBid_volume4(String.valueOf(BigDecimalUtils.round(Double.parseDouble(modelRealTime.getBid_volume4()) / 100, 0)));
            modelRealTime.setBid_volume5(String.valueOf(BigDecimalUtils.round(Double.parseDouble(modelRealTime.getBid_volume5()) / 100, 0)));
            //成交量（玩手）
            modelRealTime.setBusiness_amount(String.valueOf(PriceHelper.div(new BigDecimal(modelRealTime.getBusiness_amount()), 1000000)));
            //成交额 亿元
            modelRealTime.setBusiness_balance(String.valueOf(PriceHelper.div(new BigDecimal(modelRealTime.getBusiness_balance()), 100000000)));
            //判断是否在交易时段
//            if(!OrderModel.checkTradeDate()){
//                modelRealTime.setStatus(CacheID.STOCK_STATUS.NOT_TRADE_TIME.getValue());
//            }
            //查询股票黑名单以及st股
            List<BlackList> black = blackListService.select(new BlackList(t->{
               t.setStockCode(finalCode);
               t.setDelFlag(BlackList.DELFLAG.NORMAL.code);
            }));
            if (CollectionUtils.isNotEmpty(black)) {
                //风险股
                modelRealTime.setStatus(CacheID.STOCK_STATUS.DANGER_STOCK.getValue());
            }
            //ST股
            if (modelRealTime.getCode_name().contains("ST") || modelRealTime.getCode_name().contains("st")) {
                modelRealTime.setStatus(CacheID.STOCK_STATUS.ST.getValue());
            }
            //涨跌幅超过百分之八不能交易
            String waveRis = redisService.get(ConfigNID.WAVE_RISK);
            if (Math.abs(Double.parseDouble(modelRealTime.getRise_pre())) > Double.parseDouble(waveRis)) {
                modelRealTime.setStatus(CacheID.STOCK_STATUS.OVER_EIGHT.getValue());
            }
        } else {
            throw new BussinessException("查询不到您要的股票，请重新输入");
        }
        return ok(modelRealTime);
    }

    /**
     * 多个股票的信息
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/stockByCode", method = RequestMethod.POST)
    public ResultEntity stockByCode(@ApiParam("股票代码集") @RequestParam(required = true) String codes) throws Exception {
        if (StringUtils.isBlank(codes)) {
            throw new Exception("股票代码不能为空");
        }
        String[] codeAttr = codes.split(",");
        List<ModelRealTime> list = new ArrayList<ModelRealTime>();
        for( String code : codeAttr){
            //获取股票信息
            ModelRealTime modelRealTime = QuotationEndpoint.realtime(code);
            modelRealTime.getLast_price();
            modelRealTime.getRise_pre();
            list.add(modelRealTime);
        }
        return ok(list);
    }

    /**
     * 分时信息
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getTrendByCode", method = RequestMethod.POST)
    public ResultEntity trend(@ApiParam("股票代码") @RequestParam(required = true) String code) throws Exception {
        ResultEntity resultEntity = new ResultEntity();
        if (StringUtils.isBlank(code)) {
            //默认给一个股票代码
            code = "000001";
        }
        //时间 9.30-11.30 13.00 - 15.00
        Integer morningStart = 930;
        Integer morningEnd = 1130;
        Integer afternoonStart = 1300;
        Integer afternoonEND = 1500;
        Integer businessAmount = 0;
        ModelRealTime modelRealTime = QuotationEndpoint.realtime(code);

        //获取股票信息
        List<ModelTrend> modelTrend = JSON.parseArray(QuotationEndpoint.trend(code), ModelTrend.class);
        if (modelTrend != null) {
            for (int i = 0; i < modelTrend.size(); i++) {
                //处理成交量，每一分钟的成交量为当前成交量-上一分钟成交量，第一条不用减
                if (i == 0) {
                    modelTrend.get(0).setAfterAmount(modelTrend.get(0).getBusiness_amount());
                }
                if (i > 0) {
                    //记录上一个时间的成交量
                    String amount = modelTrend.get(i).getBusiness_amount();
                    //成交量 = 当前时间的成交量 - 上一个时间的成交量
                    //当前
                    Integer now = Integer.valueOf(modelTrend.get(i).getBusiness_amount());
                    //上一个时间
                    Integer last = Integer.valueOf(modelTrend.get(i - 1).getBusiness_amount());
                    //计算当前成交量- 上一个时间的成交量(手)
                    Integer sub = (now - last) / 100;
                    modelTrend.get(i).setAfterAmount(String.valueOf(sub));
//                    modelTrend.get(i).setBusiness_amount(String.valueOf((Integer.parseInt(modelTrend.get(i).getBusiness_amount()) - Integer.parseInt(modelTrend.get(i-1).getBusiness_amount()))/100));
                    StringBuffer sb = new StringBuffer(String.valueOf(morningStart));
                    if (sb.length() == 3) {
                        sb.insert(1, ":");
                    } else if (sb.length() == 4) {
                        sb.insert(2, ":");
                    }
                    modelTrend.get(i).setTime(String.valueOf(sb));
                    morningStart = morningStart + 1;
                    if (morningStart % 100 == 60) {
                        morningStart = (morningStart / 100 + 1) * 100;
                    }
                    if (morningStart == 1131) {
                        morningStart = afternoonStart;
                    }
                    if (modelRealTime != null) {
                        modelTrend.get(i).setPrev_price(modelRealTime.getPrev_price());
                    }
                }
            }
            modelTrend.remove(0);
        } else {
            throw new BussinessException("查询不到您要的股票，请重新输入");
        }
        return ok(modelTrend);
    }

    /**
     * 分时信息
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getTrendByCodePc", method = RequestMethod.POST)
    public ResultEntity trendPc(@ApiParam("股票代码") @RequestParam(required = true) String code) throws Exception {
        ResultEntity resultEntity = new ResultEntity();
        if (StringUtils.isBlank(code)) {
            //默认给一个股票代码
            code = "000001";
        }
        //时间 9.30-11.30 13.00 - 15.00
        Integer morningStart = 931;
        Integer morningEnd = 1130;
        Integer afternoonStart = 1301;
        Integer afternoonEND = 1500;
        Integer businessAmount = 0;
        ModelRealTime modelRealTime = QuotationEndpoint.realtime(code);

        //获取股票信息
        List<ModelTrend> modelTrend = JSON.parseArray(QuotationEndpoint.trend(code), ModelTrend.class);
        if (modelTrend != null) {
            for (int i = 0; i < modelTrend.size(); i++) {
                //处理成交量，每一分钟的成交量为当前成交量-上一分钟成交量，第一条不用减
                if (i == 0) {
                    modelTrend.get(0).setAfterAmount(String.valueOf(Integer.parseInt(modelTrend.get(0).getBusiness_amount()) / 100));
                    modelTrend.get(0).setTime("9:30");
                }
                if (i > 0) {
                    //记录上一个时间的成交量
                    //成交量 = 当前时间的成交量 - 上一个时间的成交量
                    //当前时间成交量
                    Integer now = Integer.valueOf(modelTrend.get(i).getBusiness_amount());
                    //上一个时间成交量
                    Integer last = Integer.valueOf(modelTrend.get(i - 1).getBusiness_amount());
                    //计算当前成交量- 上一个时间的成交量(手)
                    Integer sub = (now - last) / 100;
                    modelTrend.get(i).setAfterAmount(String.valueOf(sub));
                    StringBuffer sb = new StringBuffer(String.valueOf(morningStart));
                    if (sb.length() == 3) {
                        sb.insert(1, ":");
                    } else if (sb.length() == 4) {
                        sb.insert(2, ":");
                    }
                    modelTrend.get(i).setTime(String.valueOf(sb));
                    morningStart = morningStart + 1;
                    if (morningStart % 100 == 60) {
                        morningStart = (morningStart / 100 + 1) * 100;
                    }
                    if (morningStart == 1131) {
                        morningStart = afternoonStart;
                    }
                    if (modelRealTime != null) {
                        modelTrend.get(i).setPrev_price(modelRealTime.getPrev_price());
                    }
                }
            }
        } else {
            throw new BussinessException("查询不到您要的股票，请重新输入");
        }
        return ok(modelTrend);
    }

    /**
     * 日k股票的信息
     * type 6，日k，7,周k，8 月k
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getKlineByCode", method = RequestMethod.POST)
    public ResultEntity kLine(@ApiParam("code") @RequestParam(required = true) String code,
                              @ApiParam("type") @RequestParam(required = true) String type) throws Exception {
        ResultEntity resultEntity = new ResultEntity();
        if (StringUtils.isBlank(code)) {
            //默认给一个股票代码
            code = "000001";
        }
        //获取股票信息
        List<ModelKline> modelKline = JSON.parseArray(QuotationEndpoint.kline(code, Integer.parseInt(type), 180, "0"), ModelKline.class);
        if (modelKline != null) {
            return ok(modelKline);
        } else {
            throw new BussinessException("查询不到您要的股票，请重新输入");
        }

    }
}
